//
//  LTDBHelper.m
//  LTIM
//
//  Created by 俊松何 on 2017/3/28.
//  Copyright © 2017年 俊松何. All rights reserved.
//

#import "LTDBHelper.h"
#import "LTCacheSQL.h"

#import "LTUser.h"
#import "LTGroup.h"
#import "LTMessage.h"
#import "LTMessageApplyBody.h"
#import "LTConversation.h"

#import "LTUserConfig.h"
#import "LTGroupConfig.h"

#import "LTError.h"
#import "LTClient.h"

#import "FMDB.h"
#import <MJExtension/MJExtension.h>

#define LTCACHEPATH  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)

static NSString *LTUserTable    = @"LTUserTable";

static NSString *LTMessageTable      = @"LTMessageTable";

static NSString *LTConversationTable = @"LTConversationTable";

//数据库文件夹 每个用户在该文件夹下创建一个数据库文件夹，问价夹里面同意创建一个ltdb.sqlite的数据库
static NSString *LTDB = @"LTDB";

//数据库名字
static NSString *ltdbname = @"ltdb.sqlite";

@interface LTDBHelper()


//@property(nonatomic,strong) FMDatabase *fmdb;

@property(nonatomic,strong) FMDatabaseQueue *fmdbQueue;

@end


static LTDBHelper *helper = nil;

@implementation LTDBHelper
+(instancetype)sharedbhelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[LTDBHelper alloc] init];
        //根据用户id创建数据库
    
        });
    return helper;
}

-(void)initDB
{
    if([LTClient sharedClient].currentUserId != nil){
        
        //数据库文件夹  每个用户创建一个文件夹存放数据库文件
        NSString *dataFilePath = [LTCACHEPATH.lastObject stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",LTDB,[LTClient sharedClient].currentUserId]];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = NO;
        // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
        BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];
        if ( !(isDir == YES && existed == YES) ) {
            // 在 cache 目录下创建一个存放数据库的目录
            [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *dbPath = [NSString stringWithFormat:@"%@/%@",dataFilePath,ltdbname];
        helper.fmdbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
        [helper CreateTable];
    }
}
-(void)CloseDB
{
    [helper.fmdbQueue close];
}

-(BOOL)CreateTable
{
  BOOL user =          [self createUserTable];
  BOOL message =       [self createMessageTable];
  BOOL conversation =  [self createConversationTable];
  BOOL apply =         [self createApplyTable];
  BOOL versaion =      [self createVersionInfoTable];
  BOOL group   =       [self createGroupTable];
  BOOL mygroup =       [self createMyGroupTable];
  BOOL UserConfig =    [self createUserConfigTable];
  BOOL groupConfig =   [self createGroupConfigTable];
  return user && message && conversation && apply && versaion && group && UserConfig && mygroup && groupConfig;
}

-(BOOL)createVersionInfoTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_VERSION_INFO_TABLE];
    }];
    return   res;
}

-(BOOL)createConversationTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
      res = [db executeUpdate:LT_SQL_CREATE_CONVERSATION_TABLE];
    }];
   return   res;
}
-(BOOL)createMessageTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_MESSAGE_TABLE];
    }];
    return   res;
}
-(BOOL)createUserTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_USER_TABLE];
    }];
    return   res;
}

-(BOOL)createApplyTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_APPLY_TABLE];
    }];
    return   res;
}

-(BOOL)createNoticeMessageTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_NotceMessage_TABLE];
    }];
    return res;
}
-(BOOL)createGroupTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_GROUP_TABLE];
    }];
    return   res;
}
-(BOOL)createMyGroupTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_MYGROUP_TABLE];
    }];
    return   res;
}

-(BOOL)clearVersionInfo
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_VERSION_INFO];
    }];
    return res;
}
-(BOOL)createUserConfigTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_UserConfig_TABLE];
    }];
    return res;
}
-(BOOL)createGroupConfigTable
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_CREATE_GroupConfig_TABLE];
    }];
    return res;
    
}



-(void)saveVersionInfoWithIP:(NSString *)ip port:(NSString *)port
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        
        [db executeUpdate:LT_SQL_DELETE_VERSION_INFO];
        
        [db executeUpdate:LT_SQL_INSERT_VERSION_INFO,ip,port];
        
    }];
    
    
}
-(void)getVersionInfoWithcompletion:(void (^)(NSString *ip, NSString *port))completionBlock
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
         FMResultSet *result = [db executeQuery:LT_SQL_SELECT_VERSION_INFO];
        if ([result next]) {
            NSString *ip =   [result stringForColumn:LongLinkIP];
            NSString *port = [result stringForColumn:LongLinkPort];
            completionBlock(ip,port);
        }else
        {
             completionBlock(nil,nil);
        }
    }];
}


//-------------------------会话存储管理------------------------------//
-(BOOL)AddConversation:(LTConversation *)conversation
{
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        
        NSString *userStr = [conversation.conversationUser mj_JSONString];
        BOOL  res =   [db executeUpdate:LT_SQL_INSERT_CONVERSATION,
                       conversation.conversationId,
                       userStr,
                       @(conversation.isTop),
                       @(conversation.isSilent),
                       conversation.digest,
                       conversation.digestUser,
                       conversation.editingMsg,
                       conversation.extra,
                       conversation.lastMsgTime,
                       @(conversation.chatType)];
        if(res){NSLog(@"conversation插入成功");}else{NSLog(@"conversation插入失败");}
    }];
    return YES;
}
//删除一个会话
-(BOOL)DeleteConversationWithConversationID:(NSString *)conversationId
{  __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
      res = [db executeUpdate:LT_SQL_DELETE_CONVERSATION,conversationId];
    }];
    return res;
}
-(NSArray<LTConversation *> *)getAllConversation
{
   __block  NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
         FMResultSet *result = [db executeQuery:LT_SQL_ALL_CONVERSATION];
        while ([result next]) {
        LTConversation *conversation  = [[LTConversation alloc] init];
        conversation.conversationId   = [result stringForColumn:LT_CONVERSATION_Id];
        NSString *userStr             = [result stringForColumn:LT_CONVERSATION_User];
        conversation.conversationUser = [LTUser mj_objectWithKeyValues:userStr];
        conversation.isTop            = [result boolForColumn:LT_CONVERSATION_isTop];
        conversation.isSilent         = [result boolForColumn:LT_CONVERSATION_isSilent];
        conversation.digest           = [result stringForColumn:LT_CONVERSATION_digest];
        conversation.digestUser       = [result stringForColumn:LT_CONVERSATION_digestUser];
        conversation.editingMsg       = [result stringForColumn:LT_CONVERSATION_editingMsg];
        conversation.lastMsgTime      = [result stringForColumn:LT_CONVERSATION_lastMsgTime];
        conversation.chatType         = [result intForColumn:LT_CONVERSATION_chatMode];
        conversation.extra            = [result stringForColumn:LT_CONVERSATION_extra];
        [tempArray addObject:conversation];
        }
        [result close];
    }];
    return tempArray;
}
-(LTConversation *)getConversationWithConversationID:(NSString *)conversationId
{
    
    __block LTConversation *conversation;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_CONVERSATION_Id,conversationId];
        while ([result next]) {
            conversation  = [[LTConversation alloc] init];
            conversation.conversationId   = [result stringForColumn:LT_CONVERSATION_Id];
            NSString *userStr             = [result stringForColumn:LT_CONVERSATION_User];
            conversation.conversationUser = [LTUser mj_objectWithKeyValues:userStr];
            conversation.isTop            = [result boolForColumn:LT_CONVERSATION_isTop];
            conversation.isSilent         = [result boolForColumn:LT_CONVERSATION_isSilent];
            conversation.digest           = [result stringForColumn:LT_CONVERSATION_digest];
            conversation.digestUser       = [result stringForColumn:LT_CONVERSATION_digestUser];
            conversation.editingMsg       = [result stringForColumn:LT_CONVERSATION_editingMsg];
            conversation.lastMsgTime      = [result stringForColumn:LT_CONVERSATION_lastMsgTime];
            conversation.chatType         = [result intForColumn:LT_CONVERSATION_chatMode];
            conversation.extra            = [result stringForColumn:LT_CONVERSATION_extra];
            
        }
        [result close];
       
    }];
    return  conversation;
   
}
-(BOOL)DeleteConversationWithConversationID:(NSString *)conversationId  deleteMessage:(BOOL)isdelete
{
    BOOL deleteMessage = YES;
    if(isdelete){
        deleteMessage = [self deleteMessageWithConversation:conversationId];
    }
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_CONVERSATION,conversationId];
    }];

    return deleteMessage && res;
}
//会话id下的所有会话标记为已读
-(void)markAllMessagesAsReadWithConversationID:(NSString *)conversationId
{
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:LT_SQL_UPDATE_ISREAD_MESSAGE_WITH_CONVERSATION_ID,conversationId];
    }];
}

//标记这个消息id的消息为已读
-(BOOL)markMessagesAsReadWithMessageId:(NSString *)MessageId
{
     __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
     res = [db executeUpdate:LT_SQL_UPDATE_ISREAD_MESSAGE_WITH_MESSAGE_ID,MessageId];
    }];
    
    return YES;

}

- (BOOL)markConversationID:(NSString *)conversation isTop:(BOOL)istop
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_SET_ISTOP_CONVERSATION_Id,@(istop),conversation];
        
    }];
    
    
    return res;
}


- (BOOL)markConversationID:(NSString *)conversation isSilent:(BOOL)isSilent
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_SET_ISSILENT_CONVERSATION_Id,@(isSilent),conversation];
    }];
    return res;


}


//得到所有未读会话数
-(NSInteger)getAllUnreadMessage
{
   __block NSInteger unReadCount = 0;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result =  [db executeQuery:LT_SQL_SELECT_MESSAGECOUNT_WITH_ALL];
        if([result next]) {
            unReadCount = [result intForColumn:TOTALCOUNT];
        }
        [result close];
    }];
    return unReadCount;
}
//得到会话id未读的会话数
-(NSInteger)getUnreadMessageWithConversationID:(NSString *)conversationId
{
    __block NSInteger unReadCount = 0;
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result =  [db executeQuery:LT_SQL_SELECT_MESSAGECOUNT_WITH_CONVERSATION_ID,conversationId];
        if([result next]) {
            unReadCount = [result intForColumn:TOTALCOUNT];
        }
        [result close];
    }];
    return unReadCount;
}

//得到会话id未读的At消息数
-(NSInteger)getAtUnreadMessageWithConversationID:(NSString *)conversationId
{
    __block NSInteger unReadCount = 0;
    
    NSLog(@"%@",LT_SQL_SELECT_ATMESSAGECOUNT_WITH_CONVERSATION_ID);
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result =  [db executeQuery:LT_SQL_SELECT_ATMESSAGECOUNT_WITH_CONVERSATION_ID,conversationId];
        if([result next]) {
            unReadCount = [result intForColumn:TOTALCOUNT];
        }
        [result close];
    }];
    return unReadCount;
}

-(NSArray<LTMessage *> *)getAtUnReadMessageConversationID:(NSString *)conversation
{
    __block  NSMutableArray *tempMessageArray = [NSMutableArray arrayWithCapacity:1];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_UNREADATMESSAGE_WITH_CONVERSATION,conversation];
        while ([result next]) {
            LTMessage *message  =  [self _messageWith:result];
            [tempMessageArray addObject:message];
        }
        [result close];
    }];
    return tempMessageArray;

}



//-------------------------消息存储管理------------------------------//

-(BOOL)AddMessage:(LTMessage *)message
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString *sinceStr  = [message.since mj_JSONString];
        NSString *targetStr = [message.target mj_JSONString];
        NSString *bodyStr   = [message.body mj_JSONString];
        
        res =   [db executeUpdate:LT_SQL_INSERT_MESSAGE,
                       message.messageId,
                       message.conversationId,
                       message.sinceUserId,
                       message.targetUserId,
                       sinceStr,
                       targetStr,
                       bodyStr,
                       @(message.direction),
                       @(message.messageType),
                       @(message.chatType),
                       @(message.status),
                       message.transContent,
                       message.extra,
                       @(message.cellType),
                       @(message.serverTime),
                       @(message.createTime),
                       @(message.isRead)];
        
        if(res){NSLog(@"message插入成功");}else{NSLog(@"message插入失败");}
    }];
    
    return res;
}
-(BOOL)addMessages:(NSArray<LTMessage *> *)messages
{
    [self.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        NSLog(@"111-----%@",[NSThread currentThread]);
        for (LTMessage *message in messages) {
            
            NSString *sinceStr  = [message.since mj_JSONString];
            NSString *targetStr = [message.target mj_JSONString];
            NSString *bodyStr   = [message.body mj_JSONString];
            
        BOOL  res =  [db executeUpdate:LT_SQL_INSERT_MESSAGE,
                     message.messageId,
                     message.conversationId,
                     message.sinceUserId,
                     message.targetUserId,
                     sinceStr,
                     targetStr,
                     bodyStr,
                     @(message.direction),
                     @(message.messageType),
                     @(message.chatType),
                     @(message.status),
                     message.transContent,
                     message.extra,
                     @(message.cellType),
                     @(message.serverTime),
                     @(message.createTime),
                     @(message.isRead)];
            
            if(res){NSLog(@"message插入成功");}else{NSLog(@"message插入失败");}
        }
    }];
    return YES;
}

- (void)updateMessage:(LTMessage *)message
           completion:(void (^)(LTMessage *aMessage, LTError *aError))CompletionBlock
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString *sinceStr  = [message.since mj_JSONString];
        NSString *targetStr = [message.target mj_JSONString];
        NSString *bodyStr   = [message.body mj_JSONString];
        
      BOOL  res =   [db executeUpdate:LT_SQL_INSERT_MESSAGE,
                 message.messageId,
                 message.conversationId,
                 message.sinceUserId,
                 message.targetUserId,
                 sinceStr,
                 targetStr,
                 bodyStr,
                 @(message.direction),
                 @(message.messageType),
                 @(message.chatType),
                 @(message.status),
                 message.transContent,
                 message.extra,
                 @(message.cellType),
                 @(message.serverTime),
                 @(message.createTime),
                 @(message.isRead)];
        LTError *lterror = nil;
        if(res){
            NSLog(@"message更新成功");}
        else{
            lterror = [LTError errorWithDescription:@"更新消息失败" code:-1];
            NSLog(@"message更新失败");
        }
        if(CompletionBlock){
        CompletionBlock(message,lterror);
        }
        
    }];

    


}




//得到会话的最后一条消息
-(LTMessage *)getlastMessageWithConversationID:(NSString *)conversationID
{
    __block LTMessage  *message = nil;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        
      FMResultSet *result =  [db executeQuery:@"SELECT * FROM t_message WHERE conversationId = ? ORDER BY createTime DESC",conversationID];
        if ([result next]) {
            message  =  [self _messageWith:result];
        }
        [result close];
    }];

    return message;
}


-(NSArray<LTMessage *> *)getMessageWithConversation:(NSString *)conversation
{
    
    __block  NSMutableArray *tempMessageArray = [NSMutableArray arrayWithCapacity:1];
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_MESSAGE_WITH_CONVERSATION,conversation];
        while ([result next]) {
           LTMessage *message  =  [self _messageWith:result];
            [tempMessageArray addObject:message];
        }
            [result close];
    }];
       return tempMessageArray;
}
-(NSArray<LTMessage *> *)getMessageWithConversation:(NSString *)conversation
                                          startTime:(double)time
                                              count:(int)count
{
    
    __block  NSMutableArray *tempMessageArray = [NSMutableArray arrayWithCapacity:1];
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_MESSAGE_WITH_CONVERSATION_PAGE,conversation,@(time),@(count)];
        while ([result next]) {
            LTMessage *message  =  [self _messageWith:result];
            [tempMessageArray addObject:message];
        }
        [result close];
    }];
    return tempMessageArray;
}
-(LTMessage *)_messageWith:(FMResultSet *)result
{
    LTMessage  *message    = [[LTMessage alloc] init];
    message.messageId      = [result stringForColumn:LT_MESSAGE_messageId];
    message.conversationId = [result stringForColumn:LT_MESSAGE_conversationId];
    message.sinceUserId     = [result stringForColumn:LT_MESSAGE_fromUserId];
    message.targetUserId    = [result stringForColumn:LT_MESSAGE_tagetUserId];
    NSString *sinceStr     = [result stringForColumn:LT_MESSAGE_since];
    message.since          = [LTUser mj_objectWithKeyValues:sinceStr];
    NSString *tagetStr     = [result stringForColumn:LT_MESSAGE_target];
    message.target         = [LTUser mj_objectWithKeyValues:tagetStr];
    message.messageType    = [result intForColumn:LT_MESSAGE_type];
    NSString *dataStr      = [result stringForColumn:LT_MESSAGE_content];
    switch (message.messageType) {
        case LTMessageTypeText:   message.body = [LTMessageTextBody mj_objectWithKeyValues:dataStr];   break;
        case LTMessageTypeImage:  message.body = [LTMessageImageBody mj_objectWithKeyValues:dataStr];  break;
        case LTMessageTypeVoice:  message.body = [LTMessageVoiceBody mj_objectWithKeyValues:dataStr];  break;
        case LTMessageTypeVideo:  message.body = [LTMessageVideoBody mj_objectWithKeyValues:dataStr];  break;
        case LTMessageTypeLocation:  message.body = [LTMessageLocationBody mj_objectWithKeyValues:dataStr];break;
        case LTMessageTypeRedBao:  message.body = [LTMessageRedEnvelopeBody mj_objectWithKeyValues:dataStr];break;
        case LTMessageTypeFile:    message.body = [LTMessageFileBody mj_objectWithKeyValues:dataStr];break;
        case LTMessageTypeLink:    message.body = [LTMessageLinkBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeBigBq:   message.body = [LTMessageBigBqBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeCallTip: message.body = [LTMessageCallTipBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypePersonCard: message.body = [LTMessagePersonCardBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeLuckMoney:  message.body = [LTMessageLuckMoneyBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeAtText:     message.body = [LTMessageAtTextBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeETHTransfer: message.body = [LTMessageETHTransferBody mj_objectWithKeyValues:dataStr];break;
        case LTMessageTypeSayhello:   message.body = [LTMessageTextBody mj_objectWithKeyValues:dataStr];   break;
        case LTMessageTypeScreenShots:
        case LTMessageTypeCreateGroup:
        case LTMessageTypeaddGroupMember:
        case LTMessageTypeaddGroupQRMember:
        case LTMessageTypedeleteGroupMember:
        case LTMessageTypechangeGroupName:
        case LTMessageTypechangeGroupnotice:
        case LTMessageTypeRECEIVERedBao:
        case LTMessageTypeMessageRevoke:
            message.body = [LTMessageGroupOperationBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeCMD:
            message.body = [LTMessageCmdBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeGzh:
            message.body = [LTMessageGZHBody mj_objectWithKeyValues:dataStr]; break;
        case LTMessageTypeShareGzh:
            message.body = [LTMessageGzhShareBody mj_objectWithKeyValues:dataStr]; break;
        default:  break;
    }
    message.direction      = [result intForColumn:LT_MESSAGE_direction];
//    message.messageType           = [result intForColumn:LT_MESSAGE_type];
    message.chatType       = [result intForColumn:LT_MESSAGE_chatMode];
    message.status         = [result intForColumn:LT_MESSAGE_status];
    message.transContent   = [result stringForColumn:LT_MESSAGE_transContent];
    message.extra          = [result stringForColumn:LT_MESSAGE_extra];
    message.cellType       = [result intForColumn:LT_MESSAGE_cellType];
    message.serverTime     = [result longForColumn:LT_MESSAGE_serverTime];
    message.createTime     = [result longForColumn:LT_MESSAGE_createTime];
    message.isRead         = [result boolForColumn:LT_MESSAGE_isRead];
    return message;
}


-(void)getMessageWithConversation:(NSString *)conversation
                        startTime:(double)time
                            count:(int)count
                       completion:(void (^)(NSArray<LTMessage *> *aMessages, LTError *aError))aCompletionBlock
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_MESSAGE_WITH_CONVERSATION_PAGE,conversation,@(time),@(count)];
        NSMutableArray *tempMessageArray = [NSMutableArray arrayWithCapacity:1];
        while ([result next]) {
            LTMessage *message  =  [self _messageWith:result];
            
            [tempMessageArray addObject:message];
        }
        [result close];
           aCompletionBlock(tempMessageArray,nil);
        
    }];
}
-(void)getmessageWithConversation:(NSString *)conversation
                        messageId:(NSString *)messageId
                            count:(int)count
                       completion:(void (^)(NSArray<LTMessage *> *aMessages, LTError *aError))aCompletionBlock
{
    
    LTMessage *message = [self getMessageWithMessageId:messageId];
    long startTime = [[NSDate date] timeIntervalSince1970] * 1000;;
    if(message != nil)
    {
     startTime = message.createTime;
    }
    [self getMessageWithConversation:conversation startTime:startTime count:count completion:aCompletionBlock];

}

//得到会话的最后一条消息
-(LTMessage *)getMessageWithMessageId:(NSString *)messageId
{
    __block LTMessage  *message = nil;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *result =  [db executeQuery:LT_SQL_SELECT_MESSAGE_WITH_MESSAGEID,messageId];
        if ([result next]) {
            message  =  [self _messageWith:result];
        }
        [result close];
    }];
    
    return message;
}


-(BOOL)deleteMessageWithMessageId:(NSString *)messageId
{
    __block BOOL res;
     [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res =  [db executeUpdate:LT_SQL_DELETE_MESSAGE_WITH_MESSAGE_ID,messageId];
     }];
    
    return res;
}

-(BOOL)deleteMessageWithConversation:(NSString *)conversationId
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res =  [db executeUpdate:LT_SQL_DELETE_MESSAGE_WITH_CONVERSATION_ID,conversationId];
    }];
    
    return res;
}



//-------------------------用户信息存储管理------------------------------//
-(BOOL)AddUser:(LTUser *)user
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        
        res = [db executeUpdate:LT_SQL_INSERT_USER,
                user.userId,
                user.name,
                user.avatar,
                user.remark,
                user.namePy,
                user.remarkPy,
                @(user.type),
                user.phone,
                user.extra,
                user.account];
        if(res){NSLog(@"user插入成功");}else{NSLog(@"user插入失败");}
        
    }];
    return res;
}

-(BOOL)deleteUser:(NSString *)userID
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_WITH_USERID,userID];
    }];
    return res;
}

-(LTUser *)getUserWithUserId:(NSString *)userId
{
     __block   LTUser *user = nil;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_USER_USERID,userId];
        while ([result next]) {
            user = [[LTUser alloc] init];
            user.userId   =  [result stringForColumn:LT_USER_userId];
            user.name     =  [result stringForColumn:LT_USER_name];
            user.avatar   =  [result stringForColumn:LT_USER_avatar];
            user.remark   =  [result stringForColumn:LT_USER_remark];
            user.namePy   =  [result stringForColumn:LT_USER_namePy];
            user.remarkPy =  [result stringForColumn:LT_USER_remarkPy];
            user.type     =  [result intForColumn:LT_USER_type];
            user.phone    =  [result stringForColumn:LT_USER_phone];
            user.extra    =  [result stringForColumn:LT_USER_extra];
            user.account  =  [result stringForColumn:LT_USER_account];
        }
        [result close];
    }];
    return user;
}


-(NSArray<LTUser *> *)getFriendUser
{
    __block  NSMutableArray *tempUserArray = [NSMutableArray arrayWithCapacity:1];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_USER_FRIEND];
        while ([result next]) {
            LTUser   *user = [[LTUser alloc] init];
            
            user.userId   =  [result stringForColumn:LT_USER_userId];
            user.name     =  [result stringForColumn:LT_USER_name];
            user.avatar   =  [result stringForColumn:LT_USER_avatar];
            user.remark   =  [result stringForColumn:LT_USER_remark];
            user.namePy   =  [result stringForColumn:LT_USER_namePy];
            user.remarkPy =  [result stringForColumn:LT_USER_remarkPy];
            user.type     =  [result intForColumn:LT_USER_type];
            user.phone    =  [result stringForColumn:LT_USER_phone];
            user.extra    =  [result stringForColumn:LT_USER_extra];
            user.account  =  [result stringForColumn:LT_USER_account];
            [tempUserArray addObject:user];
        }
        [result close];
    }];
    return tempUserArray;
}

-(void)updateUser:(NSArray *)userArray
{
    
    [self.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        BOOL deleteres =  [db executeUpdate:LT_SQL_DELETE_ALLUSER];
        BOOL addres = YES;
        for (LTUser *user in userArray) {
            addres = addres && [db executeUpdate:LT_SQL_INSERT_USER,
                                           user.userId,
                                           user.name,
                                           user.avatar,
                                           user.remark,
                                           user.namePy,
                                           user.remarkPy,
                                           @(user.type),
                                           user.phone,
                                           user.extra,
                                           user.account];
            
            }
            *rollback = !(addres && deleteres);
        
        }];
    
    
}
-(BOOL)isFriendWithUserId:(NSString *)userId
{
    
    __block NSInteger isfriend = 0;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result =  [db executeQuery:LT_SQL_CHECKFRIEND_USERID,userId];
        if([result next]) {
            isfriend = [result intForColumn:TOTALCOUNT];
        }
        [result close];
    }];
    return isfriend ? YES : NO;
}

-(BOOL)isFriendWithAccount:(NSString *)account
{
    return NO;
}


-(BOOL)addApplyMessage:(LTMessageApplyBody *)applyMessage
{
    
     __block BOOL res;
    NSString *sinceUser = [applyMessage.since mj_JSONString];
    NSString *targetUser = [applyMessage.target mj_JSONString];
    
    [self deleteAppleMessageFromSinceUserId:applyMessage.sinceUserId];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
       res = [db executeUpdate:LT_SQL_INSERT_APPLY,
                               applyMessage.applyMessageId,
                               sinceUser,
                               targetUser,
                               applyMessage.sinceUserId,
                               applyMessage.targetUserId,
                               applyMessage.reason,
                               @(applyMessage.status),
                               @(applyMessage.isRead),
                               @(applyMessage.type),
                               @(applyMessage.createTime)];
    }];
    return res;
}

-(BOOL)deleteAppleMessageFromSinceUserId:(NSString *)sinceUserId
{
     __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_APPLTY_MESSAGEID_SINCE,sinceUserId];
    }];
    return res;
}


//删除一条申请消息
-(BOOL)deleteAppleMessage:(NSString *)applyMessageId
{
     __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_APPLTY_MESSAGEID,applyMessageId];
    }];
    return res;
}


-(BOOL)addApplyMessages:(NSArray<LTMessageApplyBody *> *)applyMessages
{
    [self.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        for (LTMessageApplyBody *applyMessage in applyMessages) {
            
            NSString *sinceUser  = [applyMessage.since mj_JSONString];
            NSString *targetUser = [applyMessage.target mj_JSONString];
//            NSString *bodyStr   = [message.body mj_JSONString];
            
          BOOL  res = [db executeUpdate:LT_SQL_INSERT_APPLY,
                                       applyMessage.applyMessageId,
                                       sinceUser,
                                       targetUser,
                                       applyMessage.sinceUserId,
                                       applyMessage.targetUserId,
                                       applyMessage.reason,
                                       @(applyMessage.status),
                                       @(applyMessage.isRead),
                                       @(applyMessage.type),
                                       @(applyMessage.createTime)];


            
            if(res){NSLog(@"message插入成功");}else{NSLog(@"message插入失败");}
        }
    }];
    return YES;
    
    
}


-(NSArray<LTMessageApplyBody *> *)getAllApplyWithUserID:(NSString *)sinceUserID
{
    __block  NSMutableArray *tempUserArray = [NSMutableArray arrayWithCapacity:1];
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_APPLY];
        while ([result next]) {
            LTMessageApplyBody   *apply = [[LTMessageApplyBody alloc] init];
            
            apply.applyMessageId = [result stringForColumn:LT_APPLY_applyMessageId];
            apply.since    = [LTUser mj_objectWithKeyValues:[result stringForColumn:LT_APPLY_since]];
            apply.target      = [LTUser mj_objectWithKeyValues:[result stringForColumn:LT_APPLY_target]];
            apply.sinceUserId     = [result stringForColumn:LT_APPLY_sinceUserId];
            apply.targetUserId  = [result stringForColumn:LT_APPLY_targetUserId];
            apply.reason  = [result stringForColumn:LT_APPLY_reason];
            apply.status      = [result intForColumn:LT_APPLY_status];
            apply.isRead      = [result boolForColumn:LT_APPLY_isRead];
            apply.type        = [result intForColumn:LT_APPLY_type];
            apply.createTime  = [result longForColumn:LT_APPLY_createTime];
            [tempUserArray addObject:apply];
        }
        [result close];
    }];
    return tempUserArray;
}
-(NSInteger)getAllUnreadApplyMessage
{

    __block NSInteger unReadCount = 0;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result =  [db executeQuery:LT_SQL_SELECT_APPLYMEMESSAGE_COUNT];
        if([result next]) {
            unReadCount = [result intForColumn:TOTALCOUNT];
        }
        [result close];
    }];
    return unReadCount;

}

-(BOOL)markAllApplyMessagesAsRead
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_UPDATE_ISREAD_APPLYMESSAGE];
    }];
    
    return YES;

}

//-------------------------小红点操作------------------------------//

-(BOOL)addNoticeMessageWithType:(LTNoticeMessageType)type
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_INSERT_NotceMessage,@(type)];
    }];
    return res;
}

-(BOOL)deleteNoticeMessageWithType:(LTNoticeMessageType)type
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_NotceMessage_WITH_TYPE,@(type)];
        
    }];
    return res;
}

-(NSInteger)getUnradNoticeMessageWithType:(LTNoticeMessageType)type
{
    __block NSInteger unReadCount = 0;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result =  [db executeQuery:LT_SQL_SELECT_NotceMessage_COUNT_WITH_TYPE,@(type)];
        if([result next]) {
            unReadCount = [result intForColumn:TOTALCOUNT];
        }
        [result close];
    }];
    return unReadCount;
}


//#define LT_SQL_INSERT_GROUP                        \
//@"INSERT OR REPLACE INTO " LT_TABLE_GROUP @" ("    \
//LT_GROUP_id                               @", "    \
//LT_GROUP_createDate                       @", "    \
/cLT_GROUP_avatar                           @", "    \
//LT_GROUP_name                             @", "    \
//LT_GROUP_ownerId                          @", "    \
//LT_GROUP_users                                     \
//@") VALUES (?,?,?,?,?,?)"

//群组操作
-(BOOL)AddGroup:(LTGroup *)group
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString *usres = [group mj_JSONString];
        res = [db executeUpdate:LT_SQL_INSERT_GROUP,group.id,group.createDate,group.avatar,group.name,group.ownerId,usres,group.qrCode];
    }];
    if(res)
    {
        NSLog(@"群组保存成功");
    }
    return res;
}

//添加群组到我自己的群组列表
-(BOOL)AddMyGroup:(LTGroup *)group
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString *usres = [group mj_JSONString];
        res = [db executeUpdate:LT_SQL_INSERT_MYGROUP,
                                   group.id,
                                   group.createDate,
                                   group.avatar,
                                   group.name,
                                   group.ownerId,
                                   usres,group.qrCode];
    }];
    if(res)
    {
        NSLog(@"my群组保存成功");
    }
    return res;


}


//删除群组
-(BOOL)deleteGroup:(NSString *)groupId
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_WITH_GROUPID,groupId];
    }];
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_WITH_MYGROUPID,groupId];
    }];
    
    return res;
}

//得到所有群组列表
-(NSArray<LTGroup *> *)getMyGroupList
{

    __block  NSMutableArray *tempUserArray = [NSMutableArray arrayWithCapacity:1];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
         FMResultSet *result  = [db executeQuery:LT_SQL_SELECT_ALL_MYGROUP];
        
        while ([result next]) {
            LTGroup *group = [[LTGroup alloc] init];
            group.id = [result stringForColumn:LT_GROUP_id];
            group.createDate = [result stringForColumn:LT_GROUP_createDate];
            group.avatar = [result stringForColumn:LT_GROUP_avatar];
            group.name = [result stringForColumn:LT_GROUP_name];
            group.ownerId = [result stringForColumn:LT_GROUP_ownerId];
            NSString *usrs = [result stringForColumn:LT_GROUP_users];
            group.users = [LTGroup mj_objectWithKeyValues:usrs].users;
            group.qrCode =  [result stringForColumn:LT_GROUP_qrCode];
            [tempUserArray addObject:group];
        }
        [result close];
    }];
    return tempUserArray;

}

//通过群ID获取群组详情
-(LTGroup *)getGroupWithGroupId:(NSString *)groupId
{
    __block LTGroup *group = nil;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result  = [db executeQuery:LT_SQL_SELECT_GROUP_id,groupId];
        if ([result next]) {
            group = [[LTGroup alloc] init];
            group.id = [result stringForColumn:LT_GROUP_id];
            group.createDate = [result stringForColumn:LT_GROUP_createDate];
            group.avatar = [result stringForColumn:LT_GROUP_avatar];
            group.name = [result stringForColumn:LT_GROUP_name];
            group.ownerId = [result stringForColumn:LT_GROUP_ownerId];
            NSString *usrs = [result stringForColumn:LT_GROUP_users];
            group.users = [LTGroup mj_objectWithKeyValues:usrs].users;
            group.qrCode =  [result stringForColumn:LT_GROUP_qrCode];

        }
         [result close];
    }];
    return group;

}

-(void)updateMyGroups:(NSArray<LTGroup *> *)groups
{
    
    [self.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        BOOL deleteres =  [db executeUpdate:LT_SQL_DELETE_MYALLGROUP];
        BOOL addres = YES;
        for (LTGroup *group in groups) {
            NSString *usres = [group mj_JSONString];
            addres = [db executeUpdate:LT_SQL_INSERT_MYGROUP,
                   group.id,
                   group.createDate,
                   group.avatar,
                   group.name,
                   group.ownerId,
                   usres,group.qrCode];
            
        }
        *rollback = !(addres && deleteres);
        
    }];
    
    
}



//好友配置信息操作
-(BOOL)AddORUpdateUserConfig:(LTUserConfig *)userConfig
{

    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_INSERT_UserConfig,
               userConfig.id,
               userConfig.friendId,
               @(userConfig.allowFriendSeeMyMoment),
               @(userConfig.shieldFriendMoment),
               @(userConfig.black),
               @(userConfig.notify),
               @(userConfig.push),
               @(userConfig.top),
               userConfig.remark,
               userConfig.chatBackground];
    }];
    if(res)
    {
        NSLog(@"userConfig保存成功");
    }
    return res;
    
}

//删除好友配置操作
-(BOOL)deleteUserConfig:(NSString *)friendId
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_UserConfig_FriendId,friendId];
    }];
    return res;
}

//通过frinedId查询UserConfig
-(LTUserConfig *)getUserConfigWithfriendId:(NSString *)friendId
{
    __block LTUserConfig *config = nil;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result  = [db executeQuery:LT_SQL_SELECT_UserConfig_WITHFriendId,friendId];
        if ([result next]) {
            config = [[LTUserConfig alloc] init];
            config.id                     = [result stringForColumn:LT_UserConfig_id];
            config.friendId               = [result stringForColumn:LT_UserConfig_friendId];
            config.allowFriendSeeMyMoment = [result boolForColumn:LT_UserConfig_allowFriendSeeMyMoment];
            config.shieldFriendMoment     = [result boolForColumn:LT_UserConfig_shieldFriendMoment];
            config.black                  = [result boolForColumn:LT_UserConfig_black];
            config.notify                 = [result boolForColumn:LT_UserConfig_notify];
            config.push                   = [result boolForColumn:LT_UserConfig_push];
            config.top                    = [result boolForColumn:LT_UserConfig_top];
            config.remark                 = [result stringForColumn:LT_UserConfig_remark];
            config.chatBackground         = [result stringForColumn:LT_UserConfig_chatBackground];
        }
        [result close];
    }];
    return config;
}


//添加群组配置信息
-(BOOL)AddOrUpdateGroupConfig:(LTGroupConfig *)groupConfig
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_INSERT_GroupConfig,
                groupConfig.id,
                groupConfig.groupId,
                groupConfig.chatBackground,
                groupConfig.myNameInGroup,
                @(groupConfig.notify),
                @(groupConfig.push),
                @(groupConfig.saveContacts),
                @(groupConfig.showUserNickname),
                @(groupConfig.top)];
    }];
    if(res)
    {
        NSLog(@"groupConfig保存成功");
    }
    return res;
    
    return YES;
}

//删除群组配置信息
-(BOOL)deleteGroupConfig:(NSString *)groupId
{
    __block BOOL res;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdate:LT_SQL_DELETE_GroupConfig_GroupId,groupId];
    }];
    return res;

}

//获取群组的配置信息
-(LTGroupConfig *)getGroupConfigWithGroupId:(NSString *)groupId
{

    __block LTGroupConfig *config = nil;
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result  = [db executeQuery:LT_SQL_SELECT_GroupConfig_WITHGroupId,groupId];
        if ([result next]) {
            config = [[LTGroupConfig alloc] init];
            config.id                     = [result stringForColumn:LT_GroupConfig_id];
            config.groupId                = [result stringForColumn:LT_GroupConfig_groupId];
            config.chatBackground         = [result stringForColumn:LT_GroupConfig_chatBackground];
            config.myNameInGroup          = [result stringForColumn:LT_GroupConfig_myNameInGroup];
            config.notify                 = [result boolForColumn:  LT_GroupConfig_notify];
            config.push                   = [result boolForColumn:  LT_GroupConfig_push];
            config.saveContacts           = [result boolForColumn:LT_GroupConfig_saveContacts];
            config.showUserNickname       = [result boolForColumn:LT_GroupConfig_showUserNickname];
            config.top                    = [result boolForColumn:LT_GroupConfig_top];
        }
        [result close];
    }];
    return config;

}


//搜索好友
-(NSArray<LTUser *> *)getUserWithKeyWorld:(NSString *)keyworld
{
    __block  NSMutableArray *tempUserArray = [NSMutableArray arrayWithCapacity:1];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSLog(@"%@",LT_SQL_SELECT_USER_FRIEND_KEYWORLD);
        NSLog(@"%@",[NSString stringWithFormat:@"%%%@%%",keyworld]);
        FMResultSet *result = [db executeQuery:LT_SQL_SELECT_USER_FRIEND_KEYWORLD,[NSString stringWithFormat:@"%%%@%%",keyworld]] ;
        while ([result next]) {
            LTUser   *user = [[LTUser alloc] init];
            user.userId   =  [result stringForColumn:LT_USER_userId];
            user.name     =  [result stringForColumn:LT_USER_name];
            user.avatar   =  [result stringForColumn:LT_USER_avatar];
            user.remark   =  [result stringForColumn:LT_USER_remark];
            user.namePy   =  [result stringForColumn:LT_USER_namePy];
            user.remarkPy =  [result stringForColumn:LT_USER_remarkPy];
            user.type     =  [result intForColumn:LT_USER_type];
            user.phone    =  [result stringForColumn:LT_USER_phone];
            user.extra    =  [result stringForColumn:LT_USER_extra];
            user.account  =  [result stringForColumn:LT_USER_account];
            [tempUserArray addObject:user];
        }
        [result close];
    }];
    return tempUserArray;
}

//搜索群
-(NSArray<LTGroup *> *)getGroupWithKeyWorld:(NSString *)keyworld
{
    __block  NSMutableArray *tempUserArray = [NSMutableArray arrayWithCapacity:1];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result  = [db executeQuery:LT_SQL_SELECT_ALL_GROUPKEYWORLD,[NSString stringWithFormat:@"%%%@%%",keyworld]];
        while ([result next]) {
            LTGroup *group = [[LTGroup alloc] init];
            group.id = [result stringForColumn:LT_GROUP_id];
            group.createDate = [result stringForColumn:LT_GROUP_createDate];
            group.avatar = [result stringForColumn:LT_GROUP_avatar];
            group.name = [result stringForColumn:LT_GROUP_name];
            group.ownerId = [result stringForColumn:LT_GROUP_ownerId];
            NSString *usrs = [result stringForColumn:LT_GROUP_users];
            group.users = [LTGroup mj_objectWithKeyValues:usrs].users;
            group.qrCode =  [result stringForColumn:LT_GROUP_qrCode];
            [tempUserArray addObject:group];
        }
        [result close];
    }];
    return tempUserArray;


}




@end
